Page({
  data: {
    searchKeyword: '',
    searchResults: [],
    totalCount: 0,
    page: 1,
    pageSize: 10,
    loading: false,
    hasMore: true,
    showFilter: false,
    sortType: 'relevance', // relevance, time, likes
    difficulty: 'all' // all, easy, medium, hard
  },

  onLoad(options) {
    const { id, keyword } = options;
    this.setData({
      searchKeyword: keyword || ''
    });
    
    if (keyword) {
      this.performSearch();
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.value || this.data.searchKeyword;
    if (keyword.trim()) {
      this.setData({
        searchKeyword: keyword,
        page: 1,
        searchResults: [],
        hasMore: true
      });
      this.performSearch();
    }
  },

  // 搜索按钮点击
  onSearchTap() {
    if (this.data.searchKeyword.trim()) {
      this.setData({
        page: 1,
        searchResults: [],
        hasMore: true
      });
      this.performSearch();
    }
  },

  // 清空输入
  onClearInput() {
    this.setData({
      searchKeyword: ''
    });
  },

  // 执行搜索
  performSearch() {
    if (this.data.loading) return;

    this.setData({
      loading: true
    });

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/recipes/list',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        pageNum: this.data.page,
        pageSize: this.data.pageSize,
        title: this.data.searchKeyword
      },
      success: (res) => {
        const ok = res.data && res.data.code === 200;
        const rows = ok ? (res.data.rows || []) : [];
        const total = ok ? (res.data.total || 0) : 0;
        const mapped = rows.map((item, idx) => {
          let imageUrl = 'https://picsum.photos/300/200?random=100';
          if (item.mediaType === 2) {
            imageUrl = item.videoDescription ? `http://localhost:8080${item.videoDescription}` : imageUrl;
          } else if (item.mediaType === 1) {
            imageUrl = item.coverUrl ? `http://localhost:8080${item.coverUrl}` : imageUrl;
          }
          return {
            id: item.id,
            title: item.title || '',
            description: item.description || '',
            imageUrl: imageUrl,
            authorName: (item.users && item.users.nickname) ? item.users.nickname : '美食达人',
            authorAvatar: (item.users && item.users.avatarUrl) ? `http://localhost:8080${item.users.avatarUrl}` : 'https://picsum.photos/60/60?random=100',
            cookTime: item.cookTime || '',
            difficulty: item.difficulty || '',
            likes: item.likeCount || 0,
            tags: []
          };
        });

        if (this.data.page === 1) {
          this.setData({
            searchResults: mapped,
            totalCount: total,
            loading: false,
            hasMore: mapped.length < total
          });
          if (mapped.length > 0) this.logSearchKeyword(this.data.searchKeyword);
        } else {
          const merged = [...this.data.searchResults, ...mapped];
          this.setData({
            searchResults: merged,
            loading: false,
            hasMore: merged.length < total
          });
        }
      },
      fail: (err) => {
        console.error('搜索接口失败', err);
        this.setData({ loading: false });
        wx.showToast({ title: '搜索失败', icon: 'none' });
      }
    });
  },

  // 去掉本地生成的模拟数据

  // 筛选按钮点击
  onFilterTap() {
    this.setData({
      showFilter: !this.data.showFilter
    });
  },

  // 排序方式改变
  onSortChange(e) {
    const sortType = e.currentTarget.dataset.type;
    this.setData({
      sortType: sortType,
      page: 1,
      searchResults: [],
      hasMore: true
    });
    this.performSearch();
  },

  // 难度等级改变
  onDifficultyChange(e) {
    const difficulty = e.currentTarget.dataset.level;
    this.setData({
      difficulty: difficulty,
      page: 1,
      searchResults: [],
      hasMore: true
    });
    this.performSearch();
  },

  // 点击搜索结果
  onResultTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/index/pages/detail/detail?id=${id}&type=search&contentType=1`
    });
  },

  // 加载更多
  onLoadMore() {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({
      page: this.data.page + 1
    });
    this.performSearch();
  },

  // 重新搜索
  onRetryTap() {
    this.setData({
      page: 1,
      searchResults: [],
      hasMore: true
    });
    this.performSearch();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      searchResults: [],
      hasMore: true
    });
    
    this.performSearch();
    
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 上拉加载更多
  onReachBottom() {
    this.onLoadMore();
  }
,

  // 搜索成功后记录关键词
  logSearchKeyword(keyword) {
    let token = '';
    let userId = null;
    try {
      token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo') || {};
      userId = userInfo.id || null;
    } catch (e) {
      console.error('读取用户信息失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/search_logs',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        userId: userId,
        keyword: keyword
      }
    });
  }
}); 